package cn.stylefeng.guns.modular.hx.storage.controller;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.hutool.http.HttpRequest;
import cn.stylefeng.guns.modular.basic.entity.BasicCustomer;
import cn.stylefeng.guns.modular.basic.entity.BasicWarehouse;
import cn.stylefeng.guns.modular.basic.model.params.BasicCustomerParam;
import cn.stylefeng.guns.modular.basic.model.params.BasicXlbOauth2tokenParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicCustomerResult;
import cn.stylefeng.guns.modular.basic.model.result.BasicXlbOauth2tokenResult;
import cn.stylefeng.guns.modular.basic.service.BasicCustomerService;
import cn.stylefeng.guns.modular.basic.service.BasicXlbOauth2tokenService;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.core.util.DateUtil;
import cn.stylefeng.guns.modular.basic.entity.BasicPosition;
import cn.stylefeng.guns.modular.basic.service.BasicPositionService;
import cn.stylefeng.guns.modular.basic.service.BasicWarehouseService;
import cn.stylefeng.guns.modular.hx.basic.entity.HxBasicGoods;
import cn.stylefeng.guns.modular.hx.basic.entity.HxBasicPositionGoods;
import cn.stylefeng.guns.modular.hx.basic.model.params.HxBasicPositionGoodsParam;
import cn.stylefeng.guns.modular.hx.basic.model.result.HxBasicPositionGoodsResult;
import cn.stylefeng.guns.modular.hx.basic.service.HxBasicGoodsService;
import cn.stylefeng.guns.modular.hx.basic.service.HxBasicPositionGoodsService;
import cn.stylefeng.guns.modular.hx.storage.entity.HxStorageStock;
import cn.stylefeng.guns.modular.hx.storage.entity.HxStorageTransfer;
import cn.stylefeng.guns.modular.hx.storage.model.params.HxStorageOffShelfParam;
import cn.stylefeng.guns.modular.hx.storage.model.params.HxStorageStockParam;
import cn.stylefeng.guns.modular.hx.storage.model.params.HxStorageTransferParam;
import cn.stylefeng.guns.modular.hx.storage.model.result.HxStorageOffShelfResult;
import cn.stylefeng.guns.modular.hx.storage.service.HxStorageMoveRecordService;
import cn.stylefeng.guns.modular.hx.storage.service.HxStorageOffShelfService;
import cn.stylefeng.guns.modular.hx.storage.service.HxStorageStockService;
import cn.stylefeng.guns.modular.hx.storage.service.HxStorageTransferService;
import cn.stylefeng.guns.sys.modular.system.entity.Dept;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.service.DeptService;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;


/**
 * 转仓管理表控制器
 *
 * @author zhucx
 * @Date 2024-02-27 22:26:23
 */
@Controller
@RequestMapping("/hxStorageTransfer")
public class HxStorageTransferController extends BaseController {

    private String PREFIX = "/hx/storage/hxStorageTransfer";

    @Autowired
    private HxStorageTransferService hxStorageTransferService;

    @Autowired
    private UserService userService;

    @Autowired
    private BasicWarehouseService basicWarehouseService;
	@Autowired
	private BasicXlbOauth2tokenService basicXlbOauth2tokenService;
	@Autowired
	private BasicCustomerService basicCustomerService;

    /**
     * 跳转到主页面
     *
     * @author zhucx
     * @Date 2024-02-27
     */
    @RequestMapping("")
    public String index(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	//查询可选择仓库
    	model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId,deliverId,user.getOperateId()));
        return PREFIX + "/hxStorageTransfer.html";
    }

    /**
     * 新增页面
     *
     * @author zhucx
     * @Date 2024-02-27
     */
    @RequestMapping("/add")
    public String add(Model model) {
    	User user = userService.getcurrentUser();
    	Long deptId = user.getDeptId();
    	Long deliverId = user.getDeliverId();
    	//查询可选择仓库
		model.addAttribute("basicWarehouseList", basicWarehouseService.findAvailableList(deptId,deliverId,user.getOperateId()));

		model.addAttribute("basicCustomerList", basicCustomerService.findAvailableList(deptId,deliverId,user.getOperateId()));

		return PREFIX + "/hxStorageTransfer_add.html";
    }

    /**
     * 编辑页面
     *
     * @author zhucx
     * @Date 2024-02-27
     */
    @RequestMapping("/edit")
    public String edit() {
        return PREFIX + "/hxStorageTransfer_edit.html";
    }

    @Autowired
    private HxStorageStockService hxStorageStockService;
    
    @Autowired
    private HxStorageMoveRecordService hxStorageMoveRecordService;

    @Autowired
    private HxStorageOffShelfService hxStorageOffShelfService;

    @Autowired
    private BasicPositionService basicPositionService;

    /**
     * 新增接口
     *
     * @author zhucx
     * @Date 2024-02-27
     */
    @RequestMapping("/addItem")
    @ResponseBody
	@Transactional(rollbackFor = Exception.class, timeout = 800000)
    public ResponseData addItem(HxStorageTransferParam hxStorageTransferParam,Integer customerId) {
    	User user = userService.getcurrentUser();
    	hxStorageTransferParam.setCreateName(user.getName());
    	hxStorageTransferParam.setCreateTimes(DateUtil.getDateS());
    	hxStorageTransferParam.setDeptId(user.getDeptId());
    	hxStorageTransferParam.setDeliverId(user.getDeliverId());

    	if(hxStorageTransferParam.getOutWarehouseId().equals(hxStorageTransferParam.getPutWarehouseId())) {
    		return ResponseData.error("转出仓库与转入仓库不可一致");
    	}
    	
    	List<String> jhlist = hxStorageMoveRecordService.findOutTask(hxStorageTransferParam.getStorageStockId());
        List<String> list1= new ArrayList<>();
        for (String s : jhlist) {
            if (ToolUtil.isNotEmpty(s)){
            	if(s.equals("待拣货")||s.equals("拣货中")) {
            		list1.add(s);
            	}
            }
        }
    	if(ToolUtil.isNotEmpty(list1)) {
    		return ResponseData.error("转出库存有拣货任务未完成，无法转仓");
    	}
		HxBasicGoods goods = hxBasicGoodsService.lambdaQuery()
				.eq(HxBasicGoods::getId, hxStorageTransferParam.getGoodsId())
				.one();
    	HxStorageOffShelfParam offShelfParam = new HxStorageOffShelfParam();
    	offShelfParam.setStockId(hxStorageTransferParam.getStorageStockId());
    	HxStorageOffShelfResult hxStorageOffShelfResult = hxStorageOffShelfService.findBySpec(offShelfParam);
    	if(hxStorageOffShelfResult != null) {
    		if(!hxStorageOffShelfResult.getStatus().equals("已完成")) {
        		if(!hxStorageOffShelfResult.getStatus().equals("作废")) {
            		return ResponseData.error("转出库存有下架任务未完成，无法转仓");
        		}
    		}
    	}
    	
    	HxStorageStock hxStorageStock = hxStorageStockService.getById(hxStorageTransferParam.getStorageStockId());
    	hxStorageTransferParam.setOutWarehouseName(hxStorageStock.getWarehouseName());
    	BigDecimal as = new BigDecimal("0");
		BigDecimal kcNum = hxStorageStock.getJibenNum();
		BigDecimal kcsum =new BigDecimal( hxStorageStock.getKcNum());
		BigDecimal nums = new BigDecimal(hxStorageTransferParam.getNum());

		BasicPosition basicPosition = basicPositionService.getById(hxStorageTransferParam.getPutPositionId());
    	hxStorageTransferParam.setPutWarehouseName(basicPosition.getWarehouseName());
		hxStorageTransferParam.setJibenUnit(goods.getJibenUnit());
		if (hxStorageTransferParam.getKcUnit().equals(goods.getKcUnit())){
			BigDecimal jibenNum = nums.multiply(new BigDecimal(goods.getKcRate())).setScale(3, BigDecimal.ROUND_HALF_DOWN);
			hxStorageTransferParam.setJibenNum(jibenNum.toString());

			BigDecimal divide = jibenNum.divide(new BigDecimal(goods.getKcRate()), 3, BigDecimal.ROUND_HALF_DOWN);
			hxStorageTransferParam.setNum(divide.toString());
		}
		if (hxStorageTransferParam.getKcUnit().equals(goods.getCgUnit())){
			BigDecimal jibenNum = nums.multiply(new BigDecimal(goods.getCgRate())).setScale(3, BigDecimal.ROUND_HALF_DOWN);
			hxStorageTransferParam.setJibenNum(jibenNum.toString());

			BigDecimal divide = jibenNum.divide(new BigDecimal(goods.getKcRate()), 3, BigDecimal.ROUND_HALF_DOWN);
			hxStorageTransferParam.setNum(divide.toString());
		}
		if (hxStorageTransferParam.getKcUnit().equals(goods.getPsUnit())){
			BigDecimal jibenNum = nums.multiply(new BigDecimal(goods.getPsRate())).setScale(3, BigDecimal.ROUND_HALF_DOWN);
			hxStorageTransferParam.setJibenNum(jibenNum.toString());

			BigDecimal divide = jibenNum.divide(new BigDecimal(goods.getKcRate()), 3, BigDecimal.ROUND_HALF_DOWN);
			hxStorageTransferParam.setNum(divide.toString());
		}
		if (hxStorageTransferParam.getKcUnit().equals(goods.getPfUnit())){
			BigDecimal jibenNum = nums.multiply(new BigDecimal(goods.getPfRate())).setScale(3, BigDecimal.ROUND_HALF_DOWN);
			hxStorageTransferParam.setJibenNum(jibenNum.toString());

			BigDecimal divide = jibenNum.divide(new BigDecimal(goods.getKcRate()), 3, BigDecimal.ROUND_HALF_DOWN);
			hxStorageTransferParam.setNum(divide.toString());
		}
		if (hxStorageTransferParam.getKcUnit().equals(goods.getJibenUnit())){
			hxStorageTransferParam.setJibenNum(nums.toString());

			BigDecimal divide = nums.divide(new BigDecimal(goods.getKcRate()), 3, BigDecimal.ROUND_HALF_DOWN);
			hxStorageTransferParam.setNum(divide.toString());

		}

		BigDecimal num = new BigDecimal(hxStorageTransferParam.getJibenNum());

		if (num.compareTo(kcNum) == 1) {
    		return ResponseData.error("转出数量不可大于库存数量");
    	}
    	boolean chenggong = false;
    	if(num.compareTo(kcNum) == 0) {
    		chenggong = true;
    		HxStorageStockParam update = new HxStorageStockParam();
    		update.setId(hxStorageStock.getId());
    		update.setWarehouseId(hxStorageTransferParam.getPutWarehouseId());
    		update.setWarehouseName(basicPosition.getWarehouseName());
    		update.setAreaId(Long.parseLong(basicPosition.getPositionAreaId().toString()));
    		update.setAreaName(basicPosition.getPositionAreaName());
    		update.setAreaNumber(basicPosition.getAreaNumber());
    		update.setPositionId(hxStorageTransferParam.getPutPositionId());
    		update.setPositionNumber(hxStorageTransferParam.getPutPositionNumber());
    		update.setPositionType(basicPosition.getPositionType());
    		update.setTransferTime(new Date());
    		hxStorageStockService.update(update);

    		if(hxStorageStock.getPositionType().equals("拣货位")) {
    			List<HxStorageStock> stocks = hxStorageStockService.lambdaQuery()
    					.eq(HxStorageStock::getPositionId, hxStorageStock.getPositionId())
    					.eq(HxStorageStock::getGoodsId, hxStorageStock.getGoodsId())
    					.list();
    			if (ToolUtil.isEmpty(stocks)){
    				HxBasicPositionGoodsParam hxBasicPositionGoodsParam = new HxBasicPositionGoodsParam();
    				hxBasicPositionGoodsParam.setPositionId(hxStorageStock.getPositionId());
    				hxBasicPositionGoodsParam.setGoodsId(hxStorageStock.getGoodsId());
    				positionGoodsService.deleteByOne(hxBasicPositionGoodsParam);
    			}
    		}
    	} 
		if (num.compareTo(kcNum) == -1) {
    		if(num.compareTo(as) == 1) {
    			chenggong = true;
    			HxStorageStockParam addStockParam = new HxStorageStockParam();
    			String trayCode = getOperateIdOrderPrefix(user)+"-";
				addStockParam.setTrayNumber(trayCode+DateUtil.getRandomNumber());//托盘编号
				addStockParam.setStockState("正常");
				addStockParam.setOperateId(hxStorageStock.getOperateId());
				addStockParam.setOperateName(hxStorageStock.getOperateName());
				addStockParam.setCustomerId(hxStorageStock.getCustomerId());
				addStockParam.setCustomerName(hxStorageStock.getCustomerName());
				addStockParam.setWarehouseId(hxStorageTransferParam.getPutWarehouseId());
				addStockParam.setWarehouseName(basicPosition.getWarehouseName());
				addStockParam.setAreaId(Long.parseLong(basicPosition.getPositionAreaId().toString()));
	    		addStockParam.setAreaName(basicPosition.getPositionAreaName());
	    		addStockParam.setAreaNumber(basicPosition.getAreaNumber());
	    		addStockParam.setPositionId(hxStorageTransferParam.getPutPositionId());
	    		addStockParam.setPositionNumber(hxStorageTransferParam.getPutPositionNumber());
	    		addStockParam.setPositionType(basicPosition.getPositionType());
				
				addStockParam.setGoodsId(hxStorageStock.getGoodsId());
				addStockParam.setGoodsName(hxStorageStock.getGoodsName());
				addStockParam.setGoodsNumber(hxStorageStock.getGoodsNumber());
				addStockParam.setGoodsPcode69(hxStorageStock.getGoodsPcode69());
				addStockParam.setGoodsSpecs(hxStorageStock.getGoodsSpecs());
				addStockParam.setGoodsBigtypeId(hxStorageStock.getGoodsBigtypeId());
				addStockParam.setGoodsBigtype(hxStorageStock.getGoodsBigtype());
				
				addStockParam.setJibenUnit(hxStorageStock.getJibenUnit());
				addStockParam.setKcUnit(hxStorageStock.getKcUnit());
				addStockParam.setKcRate(hxStorageStock.getKcRate());
				addStockParam.setCgUnit(hxStorageStock.getCgUnit());
				addStockParam.setCgRate(hxStorageStock.getCgRate());
				addStockParam.setPfUnit(hxStorageStock.getPfUnit());
				addStockParam.setPfRate(hxStorageStock.getPfRate());
				addStockParam.setPsUnit(hxStorageStock.getPsUnit());
				addStockParam.setPsRate(hxStorageStock.getPsRate());
				addStockParam.setDetailedDate(hxStorageStock.getDetailedDate());
				addStockParam.setGoodsWarranty(hxStorageStock.getGoodsWarranty());
				
				addStockParam.setSetUnitId(hxStorageStock.getSetUnitId());
				addStockParam.setSetUnit(hxStorageStock.getSetUnit());
				addStockParam.setDeptId(user.getDeptId());
				addStockParam.setDeliverId(user.getDeliverId());

				BigDecimal goodsVolume = new BigDecimal(hxStorageStock.getGoodsVolume());
				BigDecimal goodsWeight = new BigDecimal(hxStorageStock.getGoodsWeight());
				BigDecimal goodsPrice = new BigDecimal(hxStorageStock.getGoodsPrice());

				if (hxStorageTransferParam.getKcUnit().equals(goods.getKcUnit())){
					BigDecimal jibenNum = nums.multiply(new BigDecimal(goods.getKcRate())).setScale(3, BigDecimal.ROUND_HALF_DOWN);
					addStockParam.setJibenNum(jibenNum);
					BigDecimal divide = jibenNum.divide(new BigDecimal(goods.getKcRate()), 3, BigDecimal.ROUND_HALF_DOWN);
					addStockParam.setKcNum(divide.toString());
				}
				if (hxStorageTransferParam.getKcUnit().equals(goods.getCgUnit())){
					BigDecimal jibenNum = nums.multiply(new BigDecimal(goods.getCgRate())).setScale(3, BigDecimal.ROUND_HALF_DOWN);
					addStockParam.setJibenNum(jibenNum);
					BigDecimal divide = jibenNum.divide(new BigDecimal(goods.getKcRate()), 3, BigDecimal.ROUND_HALF_DOWN);
					addStockParam.setKcNum(divide.toString());
				}
				if (hxStorageTransferParam.getKcUnit().equals(goods.getPsUnit())){
					BigDecimal jibenNum = nums.multiply(new BigDecimal(goods.getPsRate())).setScale(3, BigDecimal.ROUND_HALF_DOWN);
					addStockParam.setJibenNum(jibenNum);
					BigDecimal divide = jibenNum.divide(new BigDecimal(goods.getKcRate()), 3, BigDecimal.ROUND_HALF_DOWN);
					addStockParam.setKcNum(divide.toString());
				}
				if (hxStorageTransferParam.getKcUnit().equals(goods.getPfUnit())){
					BigDecimal jibenNum = nums.multiply(new BigDecimal(goods.getPfRate())).setScale(3, BigDecimal.ROUND_HALF_DOWN);
					addStockParam.setJibenNum(jibenNum);
					BigDecimal divide = jibenNum.divide(new BigDecimal(goods.getKcRate()), 3, BigDecimal.ROUND_HALF_DOWN);
					addStockParam.setKcNum(divide.toString());
				}
				if (hxStorageTransferParam.getKcUnit().equals(goods.getJibenUnit())){
					addStockParam.setJibenNum(nums);
					BigDecimal divide = nums.divide(new BigDecimal(goods.getKcRate()), 3, BigDecimal.ROUND_HALF_DOWN);
					addStockParam.setKcNum(divide.toString());
				}
				addStockParam.setGoodsVolume(goodsVolume.toString());
				addStockParam.setGoodsWeight(goodsWeight.toString());
				addStockParam.setGoodsPrice(goodsPrice.toString());
				addStockParam.setTransferTime(new Date());
				addStockParam.setStockVolume(goodsVolume.multiply(nums).setScale(4, BigDecimal.ROUND_HALF_DOWN).toString());
				addStockParam.setStockWeight(goodsWeight.multiply(nums).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
				addStockParam.setStockMoney(goodsPrice.multiply(nums).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());

				hxStorageStockService.add(addStockParam);

				BigDecimal zcNum = new BigDecimal(hxStorageTransferParam.getNum());

		    	BigDecimal subNum = kcsum.subtract(zcNum).setScale(3, BigDecimal.ROUND_HALF_DOWN);
        		HxStorageStockParam update = new HxStorageStockParam();
        		update.setId(hxStorageStock.getId());
        		update.setKcNum(subNum.toString());
        		update.setJibenNum(subNum.multiply(new BigDecimal(hxStorageStock.getKcRate())));
        		update.setStockVolume(goodsVolume.multiply(subNum).setScale(4, BigDecimal.ROUND_HALF_DOWN).toString());
        		update.setStockWeight(goodsWeight.multiply(subNum).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
        		update.setStockMoney(goodsPrice.multiply(subNum).setScale(3, BigDecimal.ROUND_HALF_DOWN).toString());
        		hxStorageStockService.update(update);
    		}
    	} 
		if (chenggong) {
			//校验库位商品绑定关系
			if(basicPosition.getPositionType().equals("拣货位")) {
                //完成库位表商品绑定
                HxBasicPositionGoodsParam positionGoodsParam = new HxBasicPositionGoodsParam();
                positionGoodsParam.setPositionId(Long.valueOf(basicPosition.getId()));
                positionGoodsParam.setPositionType("拣货位");
                positionGoodsParam.setGoodsId(hxStorageStock.getGoodsId());
                HxBasicPositionGoodsResult positionGoodsResult = positionGoodsService.findBySpec(positionGoodsParam);
                if (ToolUtil.isEmpty(positionGoodsResult)){
                    HxBasicPositionGoods hxBasicPositionGoods = new HxBasicPositionGoods();
                    hxBasicPositionGoods.setWarehouseId(Long.valueOf(basicPosition.getWarehouseId()));
                    hxBasicPositionGoods.setAreaId(Long.parseLong(basicPosition.getPositionAreaId().toString()));
                    hxBasicPositionGoods.setAreaName(basicPosition.getPositionAreaName());
                    hxBasicPositionGoods.setPositionId(hxStorageTransferParam.getPutPositionId());
                    hxBasicPositionGoods.setPositionNumber(hxStorageTransferParam.getPutPositionNumber());
                    hxBasicPositionGoods.setPositionPickingorder(basicPosition.getPositionPickingorder());
                    hxBasicPositionGoods.setGoodsId(hxStorageStock.getGoodsId());
                    hxBasicPositionGoods.setGoodsName(hxStorageStock.getGoodsName());
                    hxBasicPositionGoods.setGoodsNumber(hxStorageStock.getGoodsNumber());
                    hxBasicPositionGoods.setGoodsPcode69(hxStorageStock.getGoodsPcode69());
                    hxBasicPositionGoods.setGoodsSpecs(hxStorageStock.getGoodsSpecs());
                    HxBasicGoods basicGoods = hxBasicGoodsService.getById(hxStorageStock.getGoodsId());
                    hxBasicPositionGoods.setAnquanNum(basicGoods.getAnquanNum());
                    hxBasicPositionGoods.setPsUnit(hxStorageStock.getPsUnit());
                    hxBasicPositionGoods.setPsRate(hxStorageStock.getPsRate());
                    hxBasicPositionGoods.setJibenUnit(hxStorageStock.getJibenUnit());
                    positionGoodsService.save(hxBasicPositionGoods);
                }
			}
		}



		BigDecimal rate = new BigDecimal(goods.getKcRate());

		BasicCustomer r = basicCustomerService.getById(customerId);
		if(ToolUtil.isNotEmpty(r.getGsnumber())&&ToolUtil.isNotEmpty(r.getStoreIdXlb())) {
			if(ToolUtil.isNotEmpty(r.getModeTms())&&r.getModeTms().equals("3")) {
				if(ToolUtil.isNotEmpty(r.getXlbStorehouseId())) {

//					HxStorageStock hxStorageStock1 = hxStorageStockService.lambdaQuery()
//							.eq(HxStorageStock::getGoodsId, goods.getId())
//							.eq(HxStorageStock::getPositionNumber, hxStorageTransferParam.getOutPositionNumber())
//							.last("LIMIT 1")
//							.one();
					// 创建订单数组
					JSONArray ordersArray = new JSONArray();

					// 创建订单对象
					JSONObject orderObject = new JSONObject();


					BasicPosition  basicPosition2= basicPositionService.lambdaQuery()
							.eq(BasicPosition::getId,hxStorageTransferParam.getPutPositionId() )
							.one();
					BasicPosition  basicPosition3= basicPositionService.lambdaQuery()
							.eq(BasicPosition::getId,hxStorageTransferParam.getOutPositionId() )
							.one();
					LocalDate productionDate = LocalDate.parse(hxStorageStock.getDetailedDate());
					// 保质期（以月份表示）
					String shelfLifeMonths =goods.getGoodsWarranty();
					LocalDateTime outputDateTime = productionDate.atStartOfDay();

					// 计算到期日期
					LocalDate expiryDate = productionDate.plusMonths(Integer.parseInt(shelfLifeMonths));

					// 格式化输出到期日期
					DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
					LocalDateTime expiryDateTime = expiryDate.atStartOfDay();

					String formattedExpiryDate = expiryDateTime.format(formatter);// 格式化输出到期日期
					String deliveryDate = outputDateTime.format(formatter);// 格式化输出生产日期

					
					BigDecimal bigDecimal = nums.multiply(rate).setScale(3, BigDecimal.ROUND_HALF_DOWN);//数量*换算率=基本数量
					orderObject.put("basic_present_quantity",0);//赠品基本数量
					orderObject.put("basic_quantity", bigDecimal);//基本数量
					orderObject.put("basic_unit", goods.getJibenUnit());// 基本单位
					orderObject.put("item_code", hxStorageTransferParam.getGoodsNumber());//商品代码
					orderObject.put("item_id", goods.getGoodsXlbId());//商品id
					orderObject.put("item_name", hxStorageTransferParam.getGoodsName());// 商品名称
					orderObject.put("present_quantity",0);// 赠品数量
					orderObject.put("present_ratio",goods.getCgRate() );//赠品换算率
					orderObject.put("present_unit", goods.getCgUnit());//赠品单位
					orderObject.put("quantity", hxStorageTransferParam.getNum());// 数量
					orderObject.put("ratio", goods.getKcRate());// 换算率
					orderObject.put("unit", hxStorageTransferParam.getKcUnit());// 单位
					orderObject.put("expire_date", formattedExpiryDate);//	到期日期
					orderObject.put("producing_date",deliveryDate);//生产日期
					orderObject.put("in_storage_id", basicPosition2.getPositionXlbId());// 转入库位id
					orderObject.put("out_storage_id", basicPosition3.getPositionXlbId());// 转出库位id
					orderObject.put("in_storage_name",basicPosition2.getPositionNumber());//转入库位名称
					orderObject.put("out_storage_name",basicPosition3.getPositionNumber());//转出库位名称

					// 将订单对象添加到订单数组中
					ordersArray.put(orderObject);

					BasicWarehouse goodsid = basicWarehouseService.lambdaQuery()
							.eq(BasicWarehouse::getId, hxStorageTransferParam.getOutWarehouseId())
							.last("LIMIT 1")
							.one();
					BasicWarehouse goodsid2 = basicWarehouseService.lambdaQuery()
							.eq(BasicWarehouse::getId, hxStorageTransferParam.getPutWarehouseId())
							.last("LIMIT 1")
							.one();
					// 创建请求参数对象
					JSONObject json = new JSONObject();
					json.put("details", ordersArray);
					json.put("in_storehouse_id", goodsid2.getWarehouseXlbId()); //入库仓库id
					json.put("memo", hxStorageTransferParam.getNote());// 备注
					json.put("move_date", hxStorageTransferParam.getTransferDate());// 转仓日期
					json.put("out_storehouse_id", goodsid.getWarehouseXlbId());//出库仓库id
					json.put("store_id", r.getStoreIdXlb());//转仓门店id
					json.put("operator", user.getName());//操作人

					//System.out.println(json);
					//	String url = "https://test-api.xlbsoft.com/api/hxl.open.wms.movestock.save";
					String url = "https://hxl-api.xlbsoft.com/api/hxl.open.wms.movestock.save";

					BasicXlbOauth2tokenParam oauth2tokenParam = new BasicXlbOauth2tokenParam();
					oauth2tokenParam.setDeliverId(r.getDeliverId());
					oauth2tokenParam.setGsnumber(r.getGsnumber());
					BasicXlbOauth2tokenResult oauth2tokenResult = basicXlbOauth2tokenService.findBySpec(oauth2tokenParam);

					String response = HttpRequest.post(url)
							.header("Authorization", "Bearer "+oauth2tokenResult.getOauth2TokenXlb())
							.body(json.toString()).execute().body();
					JSONObject jsonObject = new JSONObject(response);
					if (jsonObject.get("code").toString().equals("0")) {
						System.out.println(jsonObject.toString());
					} else {
						System.out.println(jsonObject.toString());
						TransactionAspectSupport.currentTransactionStatus().setRollbackOnly(); //手动回滚
						return ResponseData.error("回传失败");
					}
	            }
			}
		}
		hxStorageTransferParam.setReturnStatus("已完成");
		hxStorageTransferParam.setKcUnit(goods.getKcUnit());
		hxStorageTransferParam.setJibenUnit(goods.getJibenUnit());
		this.hxStorageTransferService.add(hxStorageTransferParam);
        return ResponseData.success();
    }
    
    @Autowired
    private HxBasicPositionGoodsService positionGoodsService;

	@Autowired
    private DeptService deptService;
	
    @Autowired
    private HxBasicGoodsService hxBasicGoodsService;
	
	/**
	 * 获取所属项目单号前缀
	 * @param user
	 * @return
	 */
	public String getOperateIdOrderPrefix(User user) {
		if(user.getOperateId() != null) {
			Dept dept = new Dept();
			dept.setOperateId(user.getOperateId());
			Dept resdept = deptService.findBySpec(dept);
			if(resdept != null) {
				if(ToolUtil.isNotEmpty(resdept.getOrderPrefix())) {
					return resdept.getOrderPrefix();
				} else {
					return user.getAccount().substring(0, 3);
				}
			} else {
				return null;
			}
		} else {
			return null;
		}
	}

    /**
     * 编辑接口
     *
     * @author zhucx
     * @Date 2024-02-27
     */
    @RequestMapping("/editItem")
    @ResponseBody
    public ResponseData editItem(HxStorageTransferParam hxStorageTransferParam) {
        this.hxStorageTransferService.update(hxStorageTransferParam);
        return ResponseData.success();
    }

    /**
     * 删除接口
     *
     * @author zhucx
     * @Date 2024-02-27
     */
    @RequestMapping("/delete")
    @ResponseBody
    public ResponseData delete(HxStorageTransferParam hxStorageTransferParam) {
        this.hxStorageTransferService.delete(hxStorageTransferParam);
        return ResponseData.success();
    }

    /**
     * 查看详情接口
     *
     * @author zhucx
     * @Date 2024-02-27
     */
    @RequestMapping("/detail")
    @ResponseBody
    public ResponseData detail(HxStorageTransferParam hxStorageTransferParam) {
        HxStorageTransfer detail = this.hxStorageTransferService.getById(hxStorageTransferParam.getId());
        return ResponseData.success(detail);
    }

    @Autowired
    private HxBasicPositionGoodsService hxBasicPositionGoodsService;

    /**
     * 查看绑定库位
     * @author zhucx
     * @Date 2024-02-27
     */
    @RequestMapping("/detailbd")
    @ResponseBody
    public ResponseData detailbd(HxBasicPositionGoodsParam hxBasicPositionGoodsParam) {
    	hxBasicPositionGoodsParam.setPositionType("拣货位");
        HxBasicPositionGoodsResult detail = hxBasicPositionGoodsService.findBySpec(hxBasicPositionGoodsParam);
        return ResponseData.success(detail);
    }

    /**
     * 查询列表
     *
     * @author zhucx
     * @Date 2024-02-27
     */
    @ResponseBody
    @RequestMapping("/list")
    public LayuiPageInfo list(HxStorageTransferParam hxStorageTransferParam,String condition,String startTime,String endTime ) {
    	User user = userService.getcurrentUser();
    	hxStorageTransferParam.setDeptId(user.getDeptId());
    	if (ToolUtil.isNotEmpty(startTime) && ToolUtil.isNotEmpty(endTime)) {
    		hxStorageTransferParam.setTimeInterval("'"+startTime+"' and '"+endTime+"'");
		} else if (startTime == null && endTime == null){
			hxStorageTransferParam.setTimeInterval("'"+DateUtil.getDate()+"' and '"+DateUtil.getDate()+"'");
		}
        return this.hxStorageTransferService.findPageBySpec(hxStorageTransferParam,condition,user.getOperateId());
    }

}


